<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI文档助手</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }
        
        .main-content {
            display: flex;
            min-height: 600px;
        }
        
        .sidebar {
            width: 300px;
            background: #f8f9fa;
            padding: 30px;
            border-right: 1px solid #e9ecef;
        }
        
        .upload-section {
            margin-bottom: 30px;
        }

        .drag-drop-area {
            border: 2px dashed #dee2e6;
            border-radius: 12px;
            padding: 30px 20px;
            text-align: center;
            background: #f8f9fa;
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
            margin-bottom: 15px;
        }

        .drag-drop-area:hover {
            border-color: #007bff;
            background: #e3f2fd;
        }

        .drag-drop-area.drag-over {
            border-color: #28a745;
            background: linear-gradient(135deg, #d4edda, #c3e6cb);
            transform: scale(1.02);
            box-shadow: 0 8px 25px rgba(40, 167, 69, 0.2);
        }

        .drag-drop-text {
            color: #6c757d;
            font-size: 16px;
            margin-bottom: 10px;
        }

        .drag-drop-area.drag-over .drag-drop-text {
            color: #155724;
            font-weight: bold;
        }

        .drag-drop-icon {
            font-size: 48px;
            color: #dee2e6;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }

        .drag-drop-area:hover .drag-drop-icon {
            color: #007bff;
        }

        .drag-drop-area.drag-over .drag-drop-icon {
            color: #28a745;
            transform: scale(1.1);
        }
        
        .upload-section h3 {
            color: #495057;
            margin-bottom: 15px;
            font-size: 1.2em;
        }
        
        .file-input-wrapper {
            position: relative;
            display: inline-block;
            width: 100%;
        }
        
        .file-input {
            display: none;
        }
        
        .file-input-label {
            display: block;
            padding: 12px 20px;
            background: #007bff;
            color: white;
            border-radius: 8px;
            cursor: pointer;
            text-align: center;
            transition: background 0.3s;
        }
        
        .file-input-label:hover {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }
        
        .upload-btn {
            width: 100%;
            padding: 12px;
            background: #28a745;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            margin-top: 10px;
            font-size: 1em;
            transition: background 0.3s;
        }
        
        .upload-btn:hover {
            background: #1e7e34;
        }
        
        .upload-btn:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }
        
        .file-list {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .file-item {
            padding: 10px;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .file-item:hover {
            background: #e9ecef;
            transform: translateY(-2px);
        }
        
        .file-item.active {
            background: #007bff;
            color: white;
        }
        
        .file-name {
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .file-info {
            font-size: 0.9em;
            opacity: 0.7;
        }
        
        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 30px;
        }
        
        .chat-messages {
            flex: 1;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            overflow-y: auto;
            max-height: 400px;
            background: #f8f9fa;
        }
        
        .message {
            margin-bottom: 15px;
            padding: 12px;
            border-radius: 8px;
        }
        
        .message.user {
            background: #007bff;
            color: white;
            margin-left: 20%;
        }
        
        .message.ai {
            background: #e9ecef;
            color: #495057;
            margin-right: 20%;
        }
        
        .chat-input-area {
            display: flex;
            gap: 10px;
        }
        
        .chat-input {
            flex: 1;
            padding: 12px;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            font-size: 1em;
        }
        
        .send-btn {
            padding: 12px 24px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1em;
            transition: background 0.3s;
        }
        
        .send-btn:hover {
            background: #0056b3;
        }
        
        .send-btn:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }
        
        .alert {
            padding: 12px 16px;
            border-radius: 8px;
            margin: 10px 0;
            font-size: 14px;
            font-weight: 500;
            animation: slideIn 0.3s ease-out;
        }
        
        .alert-success {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            border: 1px solid #4CAF50;
        }
        
        .alert-error {
            background: linear-gradient(135deg, #f44336, #d32f2f);
            color: white;
            border: 1px solid #f44336;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #007bff;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 AI文档助手</h1>
            <p>上传文档，与AI智能对话</p>
        </div>
        
        <!-- 错误信息显示 -->
        <div th:if="${errorMessage}" class="alert alert-error" style="margin: 20px;">
            <strong>⚠️ 系统提示：</strong> <span th:text="${errorMessage}"></span>
        </div>
        
        <div class="main-content">
            <div class="sidebar">
                <div class="upload-section">
                    <h3>📁 上传文档</h3>
                    <div id="dragDropArea" class="drag-drop-area">
                        <div class="drag-drop-icon">📁</div>
                        <div class="drag-drop-text">拖拽文件到此处或点击选择文件</div>
                        <div style="font-size: 14px; color: #adb5bd;">支持 PDF、Word、TXT 格式，最大 50MB</div>
                    </div>
                    <div class="file-input-wrapper">
                        <input type="file" id="fileInput" class="file-input" accept=".pdf,.doc,.docx,.txt" title="只支持PDF、Word文档和TXT文件">
                        <label for="fileInput" class="file-input-label">或点击此处选择文件</label>
                    </div>
                    <button id="uploadBtn" class="upload-btn" disabled>上传文件</button>
                    <div id="uploadStatus"></div>
                </div>
                
                <div class="file-list-section">
                    <h3>📄 文档列表</h3>
                    <button id="clearAllBtn" class="upload-btn" style="background:#dc3545;margin-bottom:10px;">清空所有文件</button>
                    <div id="fileList" class="file-list">
                        <div th:each="file : ${files}" class="file-item" th:data-id="${file.id}">
                            <div class="file-name" th:text="${file.originalName != null ? file.originalName : '未知文件'}"></div>
                            <div class="file-info">
                                <span th:text="${file.fileType ?: '未知类型'}"></span>
                                <span> | </span>
                                <span th:text="${file.uploadTime != null ? file.uploadTime.toString().substring(0, 16).replace('T', ' ') : '未知时间'}"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="chat-area">
                <h3>💬 AI对话</h3>
                <div id="chatMessages" class="chat-messages">
                    <div class="message ai">
                        <strong>AI助手：</strong>您好！请先选择一个文档，然后您可以向我提问关于文档内容的任何问题。
                    </div>
                </div>
                
                <div class="chat-input-area">
                    <input type="text" id="chatInput" class="chat-input" placeholder="请输入您的问题..." disabled>
                    <button id="sendBtn" class="send-btn" disabled>发送</button>
                </div>
                
                <div id="loading" class="loading">
                    <div class="spinner"></div>
                    <p>AI正在思考中...</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        let selectedFileId = null;
        
        // 拖拽上传功能
        function initDragAndDrop() {
            const dragDropArea = document.getElementById('dragDropArea');
            const fileInput = document.getElementById('fileInput');
            
            // 防止默认拖拽行为
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dragDropArea.addEventListener(eventName, preventDefaults, false);
                document.body.addEventListener(eventName, preventDefaults, false);
            });
            
            // 高亮拖拽区域
            ['dragenter', 'dragover'].forEach(eventName => {
                dragDropArea.addEventListener(eventName, highlight, false);
            });
            
            ['dragleave', 'drop'].forEach(eventName => {
                dragDropArea.addEventListener(eventName, unhighlight, false);
            });
            
            // 处理文件拖拽
            dragDropArea.addEventListener('drop', handleDrop, false);
            
            // 点击拖拽区域触发文件选择
            dragDropArea.addEventListener('click', () => {
                fileInput.click();
            });
            
            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }
            
            function highlight(e) {
                dragDropArea.classList.add('drag-over');
                const dragText = dragDropArea.querySelector('.drag-drop-text');
                const dragIcon = dragDropArea.querySelector('.drag-drop-icon');
                dragText.textContent = '松开鼠标即可上传文件';
                dragIcon.textContent = '📤';
            }
            
            function unhighlight(e) {
                dragDropArea.classList.remove('drag-over');
                const dragText = dragDropArea.querySelector('.drag-drop-text');
                const dragIcon = dragDropArea.querySelector('.drag-drop-icon');
                dragText.textContent = '拖拽文件到此处或点击选择文件';
                dragIcon.textContent = '📁';
            }
            
            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                
                if (files.length > 0) {
                    handleFiles(files[0]);
                }
            }
            
            function handleFiles(file) {
                // 模拟文件输入选择
                const dataTransfer = new DataTransfer();
                dataTransfer.items.add(file);
                fileInput.files = dataTransfer.files;
                
                // 触发文件选择事件
                const event = new Event('change', { bubbles: true });
                fileInput.dispatchEvent(event);
            }
        }
        
        // 初始化拖拽功能
        initDragAndDrop();
        
        // 文件选择
        document.getElementById('fileInput').addEventListener('change', function(e) {
            const uploadBtn = document.getElementById('uploadBtn');
            const uploadStatus = document.getElementById('uploadStatus');
            
            if (!e.target.files.length) {
                uploadBtn.disabled = true;
                uploadStatus.innerHTML = '';
                return;
            }
            
            const file = e.target.files[0];
            const fileName = file.name.toLowerCase();
            const allowedExtensions = ['.pdf', '.doc', '.docx', '.txt'];
            
            // 检查文件扩展名
            const isValidFile = allowedExtensions.some(ext => fileName.endsWith(ext));
            
            if (!isValidFile) {
                uploadStatus.innerHTML = '<div class="alert alert-error">不支持的文件格式！请选择PDF、Word文档或TXT文件。</div>';
                uploadBtn.disabled = true;
                e.target.value = ''; // 清空文件选择
                return;
            }
            
            // 检查文件大小 (50MB限制)
            const maxSize = 50 * 1024 * 1024; // 50MB
            if (file.size > maxSize) {
                uploadStatus.innerHTML = '<div class="alert alert-error">文件大小超过50MB限制！</div>';
                uploadBtn.disabled = true;
                e.target.value = ''; // 清空文件选择
                return;
            }
            
            uploadStatus.innerHTML = '<div class="alert alert-success">文件格式正确，可以上传。</div>';
            uploadBtn.disabled = false;
        });
        
        // 文件上传
        document.getElementById('uploadBtn').addEventListener('click', function() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            if (!file) return;
            
            const formData = new FormData();
            formData.append('file', file);
            
            const uploadBtn = this;
            const uploadStatus = document.getElementById('uploadStatus');
            
            uploadBtn.disabled = true;
            uploadBtn.textContent = '上传中...';
            
            fetch('/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    uploadStatus.innerHTML = '<div class="alert alert-success">文件上传成功！</div>';
                    setTimeout(() => location.reload(), 1000);
                } else {
                    uploadStatus.innerHTML = '<div class="alert alert-error">' + data.message + '</div>';
                }
            })
            .catch(error => {
                uploadStatus.innerHTML = '<div class="alert alert-error">上传失败：' + error.message + '</div>';
            })
            .finally(() => {
                uploadBtn.disabled = false;
                uploadBtn.textContent = '上传文件';
            });
        });
        
        // 文件选择
        document.querySelectorAll('.file-item').forEach(item => {
            item.addEventListener('click', function() {
                document.querySelectorAll('.file-item').forEach(i => i.classList.remove('active'));
                this.classList.add('active');
                selectedFileId = this.dataset.id;
                
                document.getElementById('chatInput').disabled = false;
                document.getElementById('sendBtn').disabled = false;
            });
        });
        
        // 发送消息
        function sendMessage() {
            if (!selectedFileId) {
                alert('请先选择一个文档');
                return;
            }
            
            const chatInput = document.getElementById('chatInput');
            const question = chatInput.value.trim();
            if (!question) return;
            
            const chatMessages = document.getElementById('chatMessages');
            const loading = document.getElementById('loading');
            const sendBtn = document.getElementById('sendBtn');
            
            // 添加用户消息
            const userMessage = document.createElement('div');
            userMessage.className = 'message user';
            userMessage.innerHTML = '<strong>您：</strong>' + question;
            chatMessages.appendChild(userMessage);
            
            chatInput.value = '';
            sendBtn.disabled = true;
            loading.style.display = 'block';
            chatMessages.scrollTop = chatMessages.scrollHeight;
            
            // 发送请求
            fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'fileId=' + selectedFileId + '&question=' + encodeURIComponent(question)
            })
            .then(response => response.json())
            .then(data => {
                const aiMessage = document.createElement('div');
                aiMessage.className = 'message ai';
                
                if (data.success) {
                    aiMessage.innerHTML = '<strong>AI助手：</strong>' + data.answer;
                } else {
                    aiMessage.innerHTML = '<strong>AI助手：</strong>抱歉，处理您的问题时出现了错误：' + (data.message || '未知错误');
                }
                
                chatMessages.appendChild(aiMessage);
                chatMessages.scrollTop = chatMessages.scrollHeight;
            })
            .catch(error => {
                const aiMessage = document.createElement('div');
                aiMessage.className = 'message ai';
                aiMessage.innerHTML = '<strong>AI助手：</strong>抱歉，网络连接出现问题：' + error.message;
                chatMessages.appendChild(aiMessage);
                chatMessages.scrollTop = chatMessages.scrollHeight;
            })
            .finally(() => {
                sendBtn.disabled = false;
                loading.style.display = 'none';
            });
        }
        
        document.getElementById('sendBtn').addEventListener('click', sendMessage);
        
        document.getElementById('clearAllBtn').addEventListener('click', function() {
            if (!confirm('确定要清空所有文件吗？此操作不可恢复！')) return;
            this.disabled = true;
            this.textContent = '清空中...';
            fetch('/api/files/clear', {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('所有文件已清空！');
                    location.reload();
                } else {
                    alert('清空失败：' + data.message);
                }
            })
            .catch(error => {
                alert('请求失败：' + error.message);
            })
            .finally(() => {
                this.disabled = false;
                this.textContent = '清空所有文件';
            });
        });
        
        document.getElementById('chatInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>